package com.andaily.web.controller.web.cooking;

import com.andaily.domain.dto.cooking.CookingAccountDto;
import com.andaily.domain.dto.cooking.CookingAccountOverviewDto;
import com.andaily.domain.dto.user.UserDto;
import com.andaily.service.CookingService;
import com.andaily.web.controller.web.validator.CookingAccountValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

/**
 * @author Shengzhao Li
 */
@Controller
@RequestMapping("/cooking")
public class CookingController {

    @Autowired
    private CookingService cookingService;

    private CookingAccountValidator validator = new CookingAccountValidator();

    @RequestMapping("/overview")
    public String overview(CookingAccountOverviewDto overviewDto, Model model) throws Exception {
        overviewDto = cookingService.loadCookingAccountOverviewDto(overviewDto);
        model.addAttribute("overviewDto", overviewDto);
        return "cooking/cooking_account_index";
    }

    @RequestMapping(value = "/form", method = RequestMethod.GET)
    public String form(String guid, Model model) throws Exception {
        CookingAccountDto cookingAccountDto = cookingService.loadCookingAccount(guid);
        model.addAttribute("cookingAccount", cookingAccountDto);

        List<UserDto> users = cookingService.loadCookingUsers();
        model.addAttribute("users", users);
        return "cooking/cooking_account_form";
    }

    @RequestMapping(value = "/form", method = RequestMethod.POST)
    public String submit(@ModelAttribute("cookingAccount") CookingAccountDto cookingAccount, BindingResult result, Model model) throws Exception {
        validator.validate(cookingAccount, result);
        if (result.hasErrors()) {
            model.addAttribute("users", cookingService.loadCookingUsers());
            return "cooking/cooking_account_form";
        }
        cookingService.persistCookingAccount(cookingAccount);
        return "redirect:overview";
    }

    @RequestMapping("/delete/{guid}")
    public String archive(@PathVariable("guid") String guid) throws Exception {
        cookingService.archiveCookingAccount(guid);
        return "redirect:../overview";
    }
}
